package com.haohe.wx.wechat.common;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.haohe.wx.model.AccessToken;
import com.haohe.wx.util.JsonDeal;
import com.haohe.wx.util.WebDataReceive;

/**
 * 
 * @Title 获取Token
 * @Description TODO
 * @author liming.zhao@haohedata.com
 * @date 2015-7-1 
 * @time 上午11:05:42
 */
public class AccessTokenServer implements TokenServer {
	
	private static Logger logger = Logger.getLogger(AccessTokenServer.class);
	@Override
	public String token() {
		String tokenJson = WebDataReceive.HTTPS.receiveData(accessTokenUrl(),null);
		if(StringUtils.isNotBlank(tokenJson)){
			AccessToken accessToken = JsonDeal.INSTANCE.jsonStr2Obj(
					tokenJson, AccessToken.class);
			if(accessToken!=null && StringUtils.isNotBlank(accessToken.getAccess_token())){
				return accessToken.getAccess_token();
			}else{
				logger.error("获取token失败；失败原因："+accessToken.getExpires_in());
			}
		}
		return null;
	}
	
	protected String accessTokenUrl() {
		String accessTokenUrl = String.format(WxConfig.getInstance().getUrl(), WxConfig.getInstance().getAppid(),WxConfig.getInstance().getAppSecret());
		logger.info("获取accessTokenUrl"+accessTokenUrl);
		return accessTokenUrl;
	}

}
